/*
 * @Author: your name
 * @Date: 2021-05-28 09:42:44
 * @LastEditTime: 2021-05-28 16:55:36
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \exam-serve\routes\class.js
 */
var express = require('express');
var router = express.Router();
var query = require('../db');
var dayjs = require('dayjs');

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/getClass', async function (req, res, next) {
  let sql = 'SELECT * FROM `class`';
  let rows = await query(sql);
  for (let i = 0; i < rows.length; i++) {
    rows[i].create_time = dayjs(rows[i].create_time).format('YYYY年MM月DD日 HH:mm:ss');
  }
  // console.log('班级查询:',rows)
  return res.json({
    code: 20000,
    data: rows,
  });
});

router.post('/classcreate', async function (req, res, next) {
  if(!req.body.XSLB){
    return res.json({
      code: 20000,
      data: {
        message: `该班级未包含任何学生，不能创建空班级！`,
        type: 'warning',
      },
    });
  }
  let sql = 'SELECT * FROM `class` where c_name=?';
  let rows = await query(sql,[req.body.c_name]);
  if(rows.length!==0){
    return res.json({
      code: 20000,
      data: {
        message: `您输入的班级“${req.body.c_name}”已存在，请重新输入！`,
        type: 'warning',
      },
    });
  }
  sql='INSERT INTO `class`(`c_name`, `admin`, `XSLB`)VALUES(?, ?, ?)'
  rows = await query(sql,[req.body.c_name,req.body.admin,req.body.XSLB]);
  console.log(req.body)
  return res.json({
    code: 20000,
    data: {
      message: `创建班级成功`,
      type: 'success',
    },
  });
});

module.exports = router;
